<?php

class CPDO{
	private $db;
	function __construct(){
		global $CONFIG;
		$dsn = 'mysql:dbname='.$CONFIG['DB']['DATABASE'].';host='.$CONFIG['DB']['HOST'].';port='.$CONFIG['DB']['PORT'];
		try {
			$this->db = new PDO($dsn, $CONFIG['DB']['USERNAME'], $CONFIG['DB']['PASSWORD']);
			$this->db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
			$this->db->exec("SET NAMES 'UTF8'");
		} catch (PDOException $e) {
			error_log('Connection failed: ' . $e->getMessage());
			
		}
	}

	public function insert($sql){
        if($this->db->exec($sql)){
            return $this->db->lastInsertId();
		}else{
			return FALSE;
		}
	}

	public function find($sql){
		$rs = $this->db->query($sql);
		$rs->setFetchMode(PDO::FETCH_OBJ);
		return $rs->fetchAll();
	}

	public function get($sql){
		$rs = $this->db->query($sql);
		$rs->setFetchMode(PDO::FETCH_OBJ);
		return $rs->fetch();
	}

	public function update($sql){
		return ($this->db->exec($sql) > 0);
	}

	public function delete($sql){
		return ($this->db->exec($sql) > 0);
	}

	public function count($table,$where = false){
		$sql = "SELECT count(*) FROM `$table`";
		if($where){
			$sql .= " WHERE " . $where;
		}
		$rs = $this->db->query($sql);
		return $rs->fetch(PDO::FETCH_COLUMN);
	}

}
